package com.dd.cloud.user.service.chknowl.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.common.constants.ChKnowlConstants;
import com.dd.cloud.common.constants.SearchConstants;
import com.dd.cloud.user.entity.chknowl.ChknowlChPatent;
import com.dd.cloud.common.interceptor.UserInterceptor;
import com.dd.cloud.user.mapper.chknowl.ChknowlChPatentMapper;
import com.dd.cloud.user.req.chknowl.ChPatentCreateReq;
import com.dd.cloud.user.req.chknowl.ChPatentQueryReq;
import com.dd.cloud.user.req.chknowl.ChPatentUpdateReq;
import com.dd.cloud.user.res.chknowl.ChUserSearchListRes;
import com.dd.cloud.user.service.chknowl.IChknowlChPatentService;
import com.dd.cloud.user.service.search.ISearchHotService;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.common.enums.ZkExceptionEnum;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.utils.ExtUtils;
import com.dd.cloud.common.utils.ObjectUtils;
import com.dd.cloud.common.utils.ValidatorUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 中成药 服务实现类
 * </p>
 *
 * @author czg
 * @since 2022-07-04
 */
@Service
public class ChknowlChPatentServiceImpl extends ServiceImpl<ChknowlChPatentMapper, ChknowlChPatent> implements IChknowlChPatentService {
    @Autowired
    private ISearchHotService searchHotService;

    /**
     * 查询中成药, 关键字查询
     *
     * @param keyword
     * @return
     */
    @Override
    public List<ChUserSearchListRes> getChPatentListByKeyword(String keyword) {
        searchHotService.saveSearchHot(SearchConstants.Modular.CHSCIENCE, SearchConstants.ChscienceSubmodule.PATENT, keyword);
        return getBaseMapper().getChPatentListByKeyword(keyword);
    }

    /**
     * 查询中成药信息列表
     *
     * @param req 条件参数
     * @return
     */
    @Override
    public IPage<ChknowlChPatent> queryMiddlePatentPage(ChPatentQueryReq req) {
        if (!StringUtils.isBlank(req.getStatus())){
            req.setStatusStr(req.getStatus().split(","));
        }
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo().get();
        req.setUserType(loginInfo.getType());
        IPage<ChknowlChPatent> iPage = req.pagePojo();
        iPage = getBaseMapper().getChPatentPage(iPage, req);
        return iPage;
    }


    /**
     * 查询中成药信息
     *
     * @param id
     * @return
     */
    @Override
    public ChknowlChPatent queryChPatentDetail(Integer id) {
        ChknowlChPatent mpd = getBaseMapper().getChknowlChPatentById(id);
        return mpd;
    }

    /**
     * 添加中成药信息
     *
     * @param req 参数
     */
    @Override
    public void createChPatent(ChPatentCreateReq req) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.ADMIN).get();
        QueryWrapper<ChknowlChPatent> qw = new QueryWrapper<>();
        qw.lambda().eq(ChknowlChPatent::getName, req.getName())
                .ne(ChknowlChPatent::getStatus, ChKnowlConstants.ContentStatus.DELETE);
        ChknowlChPatent mpd = getOne(qw);
        if (mpd != null){
            throw new ZekeException(400, "药品名已存在");
        }
        mpd = new ChknowlChPatent();
        BeanUtils.copyProperties(req, mpd);
        mpd.setCreateDate(LocalDateTime.now());
        mpd.setOperId(loginInfo.getId());
        mpd.setOperDate(LocalDateTime.now());
        mpd.setCreateDate(LocalDateTime.now());
        mpd.setStatus(ChKnowlConstants.ContentStatus.NORMAL);
        boolean flag = save(mpd);
        if (!flag) {
            throw new ZekeException(ZkExceptionEnum.ADD_ERROR);
        }
    }

    /**
     * 修改中成药信息
     *
     * @param req 参数
     */
    @Override
    public void updateChPatent(ChPatentUpdateReq req) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.ADMIN).get();
        ChknowlChPatent mpd = getById(req.getId());
        if (mpd == null || mpd.getStatus() == ChKnowlConstants.ContentStatus.DELETE){
            throw new ZekeException(400, "中成药信息不存在");
        }
        if (!mpd.getName().equals(req.getName())){
            //修改了药品名, 判断药品名是否存在
            QueryWrapper<ChknowlChPatent> qw = new QueryWrapper<>();
            qw.lambda().eq(ChknowlChPatent::getName, req.getName())
                    .ne(ChknowlChPatent::getStatus, ChKnowlConstants.ContentStatus.DELETE);
            ChknowlChPatent patent = getOne(qw);
            if (patent != null){
                throw new ZekeException(400, "药品名已存在");
            }
        }
        BeanUtils.copyProperties(req, mpd);
        mpd.setOperId(loginInfo.getId());
        mpd.setOperDate(LocalDateTime.now());
        boolean flag = updateById(mpd);
        if (!flag) {
            throw new ZekeException(ZkExceptionEnum.UPDATE_ERROR);
        }
    }

    /**
     * 修改中成药信息状态
     *
     * @param id     id
     * @param status 状态
     */
    @Override
    public void updateChPatentStatus(Integer id, Integer status) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.ADMIN).get();
        ChknowlChPatent mpd = getById(id);
        if (mpd == null || mpd.getStatus() == ChKnowlConstants.ContentStatus.DELETE){
            throw new ZekeException(400, "中成药信息不存在");
        }
        if (!ObjectUtils.refrect(ChKnowlConstants.ContentStatus.class, status)){
            throw new ZekeException(ZkExceptionEnum.STATUS_DATA_ERROR);
        }
        mpd.setOperId(loginInfo.getId());
        mpd.setOperDate(LocalDateTime.now());
        mpd.setStatus(status);
        boolean flag = updateById(mpd);
        if (!flag) {
            throw new ZekeException(ZkExceptionEnum.UPDATE_ERROR);
        }
    }

    /**
     * excel批量导入中成药信息
     *
     * @param file excel文件
     */
    @Override
    public void importChPatent(MultipartFile file) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo(LoginInfo.UserType.ADMIN).get();
        List<ChknowlChPatent> list = new ArrayList<>();
        try {
            if (file == null) {
                throw new ZekeException(400, "请上传文件");
            }
            list = ExtUtils.importExcel(file, 0, 1, ChknowlChPatent.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new ZekeException(400, "解析Excel失败");
        }
        List<String> exists = getBaseMapper().getChknowlChPatentNameIsExists(list.stream().map(ChknowlChPatent::getName).collect(Collectors.toList()));
        if (exists != null && !exists.isEmpty()){
            throw new ZekeException(400, "以下药品名已存在:"+ StringUtils.join(exists, ","));
        }
        list.stream().forEach(patent -> {
            ValidatorUtils.verify(patent, ChknowlChPatent.class);
            patent.setStatus(ChKnowlConstants.ContentStatus.NORMAL);
            patent.setCreateDate(LocalDateTime.now());
            patent.setOperId(loginInfo.getId());
            patent.setOperDate(LocalDateTime.now());
        });
        int flag = getBaseMapper().insertBatchSomeColumn(list);
        if (flag <= 0) {
            throw new ZekeException(400, "批量导入数据失败");
        }
    }
}
